using System.Collections;
using System;
using Evaluant.Uss.Domain;

namespace Evaluant.Uss.Cache
{
	public class IdentityMapEnumerator : IDictionaryEnumerator
	{
		private IDictionaryEnumerator innerEnumerator;
		
		internal IdentityMapEnumerator(IdentityMap enumerable)
		{
			innerEnumerator = enumerable.InnerHash.GetEnumerator();
		}
		
		#region Implementation of IDictionaryEnumerator
		public object Key 
		{
			get 
			{
				return innerEnumerator.Key;
			}
		}
		
		object IDictionaryEnumerator.Key 
		{
			get 
			{
				return Key;
			}
		}
		
		public Entity Value 
		{
			get 
			{
                WeakReference weakref = ((DictionaryEntry)innerEnumerator.Value).Value as WeakReference;

                // Get a reference to block its releasing
                Entity target = (Entity)weakref.Target;

                if (weakref.IsAlive)
                    return target;
                else
                    return null;
			}
		}
		
		object IDictionaryEnumerator.Value 
		{
			get 
			{
				return Value;
			}
		}
		
		public DictionaryEntry Entry 
		{
			get 
			{
				return innerEnumerator.Entry;
			}
		}
		#endregion
		
		#region Implementation of IEnumerator
		public void Reset()
		{
			innerEnumerator.Reset();
		}
		
		public bool MoveNext()
		{
			return innerEnumerator.MoveNext();
		}
		
		public object Current 
		{
			get 
			{
				                WeakReference weakref = ((DictionaryEntry)innerEnumerator.Current).Value as WeakReference;

                // Get a reference to block its releasing
                Entity target = (Entity)weakref.Target;

                if (weakref.IsAlive)
                    return target;
                else
                    return null;
			}
		}
		#endregion
	}
}
